<!DOCTYPE html>
<html>
<head>
    <title>学生管理系统</title>
    <meta charset="UTF-8">
    <script src="../../js/main.js"></script>

    <style>
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .search-box {
            display: flex;
            gap: 10px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .table th, .table td {
            padding: 12px;
            border: 1px solid #e0e0e0;
            text-align: left;
        }

        .table th {
            background-color: #f5f5f5;
            font-weight: 500;
        }

        .pagination {
            margin-top: 25px;
            text-align: center;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            background-color: #4a90e2;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
        }

        .btn-danger {
            background-color: #ff4d4f;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            position: relative;
            background-color: #fff;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 700px;
            border-radius: 8px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
        }

        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .course-list {
            max-height: 400px;
            overflow-y: auto;
            margin: 15px 0;
        }

        .course-category {
            padding: 10px;
            background-color: #f8f9fa;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .course-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
        }

        .course-item:hover {
            background-color: #f0f2f5;
        }

        .course-checkbox {
            margin-right: 15px;
        }

        .course-grade {
            width: 60px;
            margin-left: 15px;
            text-align: center;
        }

        .grade-label {
            margin-left: 10px;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 头部区域 -->
    <div class="header">
        <!-- 搜索栏 -->
        <div class="search-box">
            <input type="text" id="studentNoSearch" placeholder="请输入学号查询" class="form-input">
            <button class="btn" onclick="searchStudents()">查询</button>
        </div>
        <!-- 新增按钮 -->
        <button class="btn" onclick="openModal('add')">新增学生</button>
    </div>

    <!-- 学生列表 -->
    <table class="table">
        <thead>
        <tr>
            <th>学号（studentNo）</th>
            <th>姓名（name）</th>
            <th>性别（gender）</th>
            <th>生日（birthday）</th>
            <th>操作栏</th>
        </tr>
        </thead>
        <tbody id="studentList"></tbody>
    </table>

    <!-- 分页栏 -->
    <div class="pagination">
        <span>当前页：<span id="currentPage">1</span> / </span>
        <span>总页数：<span id="totalPages">--</span>,</span>
        <span>每页显示：
                <select id="pageSize" onchange="changePageSize()">
                    <option value="5">5</option>
                    <option value="10">10</option>
                    <option value="15">15</option>
                </select> 条
            </span>
        <button class="btn" onclick="prevPage()" id="prevBtn" disabled>上一页</button>
        <button class="btn" onclick="nextPage()" id="nextBtn" disabled>下一页</button>
    </div>
</div>

<!-- 模态框（新增/编辑窗口） -->
<div id="myModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal()">&times;</span>
        <h2 id="modalTitle">新增学生</h2>
        <form id="studentForm">
            <input type="hidden" id="studentNoHidden">
            <div class="form-group">
                <label>学号：</label>
                <input type="number" id="studentNo" name="studentNo" required>
            </div>
            <div class="form-group">
                <label>姓名：</label>
                <input type="text" id="name" name="name" required>
            </div>
            <div class="form-group">
                <label>性别：</label>
                <input type="text" id="gender" name="gender" required>
            </div>
            <div class="form-group">
                <label>生日（YYYY-MM-DD）：</label>
                <input type="date" id="birthday" name="birthday" required>
            </div>
            <button type="button" class="btn" onclick="saveStudent()">保存</button>
        </form>
    </div>
</div>

<!-- 课程分配模态框 -->
<div id="courseModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeCourseModal()">&times;</span>
        <h2 id="courseModalTitle">课程分配</h2>
        <div class="form-group">
            <label>学生：</label>
            <span id="courseModalStudentInfo"></span>
        </div>
        <div class="course-list" id="courseList"></div>
        <div class="form-group">
            <label>成绩录入（选填）：</label>
            <small>仅对已选课程有效</small>
        </div>
        <button type="button" class="btn" onclick="saveCourseAssignment()">保存分配</button>
        <button type="button" class="btn btn-secondary" onclick="closeCourseModal()">取消</button>
    </div>
</div>

<!-- jQuery库 -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>

    // 初始化加载数据
    $(document).ready(() => {
        loadStudents();
    });
    currentPage = 1;
    pageSize = 10;
    totalPages = 1;

    // 加载学生列表
    function loadStudents() {
        $.ajax({
            type: "GET",
            url: `${API_URL}/pageStudent`,
            data: {
                studentNo: $("#studentNoSearch").val(),
                current: currentPage,
                size: pageSize
            },
            success: (res) => {
                renderList(res.records);
                updatePagination(res);
            },
            error: (err) => {
                console.error("加载数据失败:", err);
                alert("加载数据失败，请检查API连接是否正常");
            }
        });
    }

    // 渲染列表（添加课程管理按钮）
    function renderList(students) {
        let html = "";
        students.forEach(student => {
            // 修正日期处理逻辑，防止空值报错
            const birthday = student.birthday
                ? new Date(student.birthday).toISOString().split('T')[0]
                : '';

            html += `
                    <tr>
                        <td>${student.studentNo}</td>
                        <td>${student.name}</td>
                        <td>${student.gender}</td>
                        <td>${birthday}</td>
                        <td>
                            <button class="btn btn-sm" onclick="openModal('edit', ${student.studentNo})">编辑</button>
                            <button class="btn btn-danger btn-sm" style="margin-left: 5px;" onclick="deleteStudent(${student.studentNo})">删除</button>
                            <button class="btn btn-sm" style="margin-left: 5px;"
                                onclick="openCourseAssignmentModal(${student.studentNo}, '${student.name}')">
                                课程管理
                            </button>
                        </td>
                    </tr>
                `;
        });
        $("#studentList").html(html);
    }

    // 更新分页
    function updatePagination(pagination) {
        currentPage = pagination.current;
        totalPages = pagination.pages;
        pageSize = pagination.size;
        const totalRecords = pagination.total;

        $("#currentPage").text(currentPage);
        $("#totalPages").text(totalPages);
        $("#pageSize").val(pageSize);

        // 按钮状态控制
        $("#prevBtn").prop("disabled", currentPage === 1);
        $("#nextBtn").prop("disabled", currentPage === totalPages);
    }

    // 搜索功能
    function searchStudents() {
        currentPage = 1;
        loadStudents();
    }

    // 分页操作
    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            loadStudents();
        }
    }

    function nextPage() {
        if (currentPage < totalPages) {
            currentPage++;
            loadStudents();
        }
    }

    function changePageSize() {
        pageSize = parseInt($("#pageSize").val());
        currentPage = 1;
        loadStudents();
    }

    // 模态框操作
    function openModal(mode, studentNo = null) {
        const modal = document.getElementById("myModal");
        modal.style.display = "block";

        if (mode === "edit") {
            $("#modalTitle").text("编辑学生");
            // 获取学生详情
            $.get(`${API_URL}/selectStudent/${studentNo}`, (student) => {
                $("#studentNoHidden").val(student.studentNo);
                $("#studentNo").val(student.studentNo).prop("readonly", true);
                $("#name").val(student.name);
                $("#gender").val(student.gender);

                // 修正日期处理逻辑
                const birthday = student.birthday
                    ? new Date(student.birthday).toISOString().split('T')[0]
                    : '';
                $("#birthday").val(birthday);
            }).fail((err) => {
                console.error("获取学生信息失败:", err);
                alert("获取学生信息失败，请重试");
                closeModal();
            });
        } else {
            $("#modalTitle").text("新增学生");
            $("#studentForm")[0].reset();
            $("#studentNo").prop("readonly", false);
        }
    }

    function closeModal() {
        document.getElementById("myModal").style.display = "none";
    }

    // 保存学生（新增/编辑）
    function saveStudent() {
        const formData = {
            studentNo: parseInt($("#studentNo").val()),
            name: $("#name").val(),
            gender: $("#gender").val(),
            birthday: $("#birthday").val()
        };

        // 验证表单数据
        if (!formData.studentNo || !formData.name || !formData.gender || !formData.birthday) {
            alert("请填写完整的学生信息");
            return;
        }

        const studentNo = $("#studentNoHidden").val();
        const url = studentNo ? `${API_URL}/updateStudent` : `${API_URL}/addStudent`;
        const method = studentNo ? "PUT" : "POST";

        $.ajax({
            type: method,
            url: url,
            contentType: "application/json",
            data: JSON.stringify(formData),
            success: (response) => {
                if (response === "success") {
                    closeModal();
                    loadStudents();
                    alert("操作成功！");
                } else {
                    alert("操作失败：" + response);
                }
            },
            error: (err) => {
                console.error("保存失败:", err);
                alert("操作失败，请检查输入或联系管理员！");
            }
        });
    }

    // 删除学生
    function deleteStudent(studentNo) {
        if (confirm("确认要删除该学生吗？")) {
            $.ajax({
                type: "DELETE",
                url: `${API_URL}/delStudent/${studentNo}`,
                success: (response) => {
                    if (response === "success") {
                        loadStudents();
                        alert("删除成功！");
                    } else {
                        alert("删除失败：" + response);
                    }
                },
                error: (err) => {
                    console.error("删除失败:", err);
                    alert("删除失败，请重试！");
                }
            });
        }
    }

    // 打开课程分配模态框
    function openCourseAssignmentModal(studentNo, studentName) {
        currentStudentNo = studentNo;
        const modal = document.getElementById("courseModal");
        modal.style.display = "block";
        $("#courseModalStudentInfo").text(`${studentNo} - ${studentName}`);

        // 重置数据
        assignedCourseNos = [];
        courseGrades = {};

        // 加载课程目录和已分配课程
        loadCourseCatalog();
        loadAssignedCourses(studentNo);
    }

    // 加载课程目录
    function loadCourseCatalog() {
        $.get(`${COURSE_CATALOG_URL}/getAllCourse`, (res) => {
            if (res.code === "200") {
                // 按分类组织课程，为无分类课程设置默认分类
                const courseCategories = {
                    "未分类": []
                };

                res.data.forEach(course => {
                    const category = course.category || "未分类";
                    if (!courseCategories[category]) {
                        courseCategories[category] = [];
                    }
                    courseCategories[category].push(course);
                });

                // 移除空的未分类组
                if (courseCategories["未分类"].length === 0) {
                    delete courseCategories["未分类"];
                }

                allCourses = courseCategories;
                renderCourseList();
            } else {
                alert("获取课程列表失败：" + (res.msg || "未知错误"));
            }
        }).fail((err) => {
            console.error("加载课程目录失败:", err);
            alert("加载课程目录失败，请检查API连接");
        });
    }

    // 加载已分配课程
    function loadAssignedCourses(studentNo) {
        $.get(`${COURSE_API_URL}/getByStudentNo`, {studentNo}, (res) => {
            if (res.code === "200") {
                assignedCourseNos = res.data;
                loadCourseGrades(studentNo);
            } else {
                alert("获取已分配课程失败：" + res.msg);
            }
        }).fail((err) => {
            console.error("加载已分配课程失败:", err);
            alert("加载已分配课程失败，请检查API连接");
        });
    }

    // 加载课程成绩
    function loadCourseGrades(studentNo) {
        $.get(`${COURSE_API_URL}/getGradesByStudentNo`, {studentNo}, (res) => {
            if (res.code === "200") {
                res.data.forEach(item => {
                    courseGrades[item.courseNo] = item.grade;
                });
                renderCourseList();
            } else {
                // 允许没有成绩数据
                renderCourseList();
            }
        }).fail((err) => {
            console.error("加载课程成绩失败:", err);
            // 允许没有成绩数据
            renderCourseList();
        });
    }

    // 渲染课程列表
    function renderCourseList() {
        let html = "";

        // 如果没有课程数据，显示提示信息
        if (Object.keys(allCourses).length === 0) {
            html = `<div class="course-category">暂无课程数据</div>`;
            $("#courseList").html(html);
            return;
        }

        // 遍历所有分类
        Object.keys(allCourses).forEach(category => {
            // 只显示有课程的分类
            if (allCourses[category].length > 0) {
                html += `<div class="course-category">${category || '未分类'}</div>`;

                // 遍历该分类下的所有课程
                allCourses[category].forEach(course => {
                    if (!course.courseNo) return; // 跳过无效课程

                    const isAssigned = assignedCourseNos.includes(course.courseNo);
                    const grade = courseGrades[course.courseNo] || "";

                    html += `
                        <div class="course-item">
                            <input type="checkbox" class="course-checkbox"
                                id="course-${course.courseNo}" value="${course.courseNo}"
                                ${isAssigned ? "checked" : ""}
                                onchange="toggleCourse(this, ${course.courseNo})">
                            <label for="course-${course.courseNo}">${course.courseName || '未命名课程'}</label>
                            <div class="grade-container">
                                <span class="grade-label">成绩：</span>
                                <input type="number" class="course-grade"
                                    id="grade-${course.courseNo}" value="${grade}"
                                    min="0" max="100" ${!isAssigned ? "disabled" : ""}>
                            </div>
                        </div>
                    `;
                });
            }
        });

        $("#courseList").html(html);
    }

    // 切换课程选择状态
    function toggleCourse(checkbox, courseNo) {
        const gradeInput = $(`#grade-${courseNo}`);
        if (checkbox.checked) {
            gradeInput.prop("disabled", false);
        } else {
            gradeInput.prop("disabled", true);
            gradeInput.val(""); // 取消选择时清空成绩
            delete courseGrades[courseNo];
        }
    }

    // 保存课程分配
    function saveCourseAssignment() {
        if (!currentStudentNo) return alert("请选择学生");

        const selectedCourses = [];
        const gradesToSave = [];

        // 收集选中课程和成绩
        $(".course-checkbox:checked").each((index, el) => {
            const courseNo = parseInt($(el).val());
            selectedCourses.push(courseNo);

            const gradeInput = $(`#grade-${courseNo}`);
            const grade = gradeInput.val().trim();
            if (grade) {
                gradesToSave.push({
                    studentNo: currentStudentNo,
                    courseNo: courseNo,
                    grade: parseFloat(grade)
                });
            }
        });

        // 1. 先保存课程分配
        $.ajax({
            type: "POST",
            url: `${COURSE_API_URL}/assignCourses`,
            contentType: "application/json",
            data: JSON.stringify({
                studentNo: currentStudentNo,
                courseNos: selectedCourses
            }),
            success: (response) => {
                if (response.code === "200") {
                    // 2. 再保存成绩（逐个提交）
                    if (gradesToSave.length > 0) {
                        saveGradesSequentially(gradesToSave, 0);
                    } else {
                        alert("课程分配成功！");
                        closeCourseModal();
                    }
                } else {
                    alert("课程分配失败：" + response.msg);
                }
            },
            error: (err) => {
                console.error("保存课程分配失败:", err);
                alert("保存课程分配失败，请检查网络连接或联系管理员");
            }
        });
    }

    // 顺序保存成绩（避免并发问题）
    function saveGradesSequentially(grades, index) {
        if (index >= grades.length) {
            alert("课程分配及成绩保存成功！");
            closeCourseModal();
            return;
        }

        const gradeData = grades[index];
        $.ajax({
            type: "POST",
            url: `${COURSE_API_URL}/addGrade`,
            contentType: "application/json",
            data: JSON.stringify(gradeData),
            success: () => {
                saveGradesSequentially(grades, index + 1);
            },
            error: (err) => {
                console.error("保存成绩失败:", err);
                alert(`第${index + 1}个成绩保存失败，可能已存在，将继续保存其他成绩`);
                saveGradesSequentially(grades, index + 1);
            }
        });
    }

    function closeCourseModal() {
        document.getElementById("courseModal").style.display = "none";
    }
</script>
</body>
</html>